package com.suning.sawp.in.controller;

import java.io.IOException;
import java.io.InputStream;
import java.security.Principal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import com.suning.framework.image.service.ImageServiceException;
import com.suning.sawp.constants.ErrorCodeConstants;
import com.suning.sawp.dto.aircondition.SNItemInfoResponseDTO;
import com.suning.sawp.dto.commodity.MssAggregationPageDto;
import com.suning.sawp.dto.commodity.MssCategory;
import com.suning.sawp.dto.commodity.MssCommodityPageResponse;
import com.suning.sawp.dto.common.ReturnMsg;
import com.suning.sawp.intf.airCondition.CommodityDetailRsfService;
import com.suning.sawp.intf.commodity.BppCommodityService;
import com.suning.sawp.intf.commodity.MssCommoditySelfService;
import com.suning.sawp.intf.model.ModelErrorConstant;
import com.suning.sawp.intf.storeman.StoreManService;
import com.suning.sawp.po.commodity.BppCommodityInfo;
import com.suning.sawp.po.commodity.MssAggregationPage;
import com.suning.sawp.po.commodity.MssCommoditySelf;
import com.suning.sawp.service.impl.contend.UIMGStore;
import com.suning.sawp.service.util.BaseContants;
import com.suning.sawp.service.util.DJStringUtils;
import com.suning.sawp.service.util.DateUtils;
import com.suning.sawp.service.util.ExcelUtils;
import com.suning.sawp.service.util.SCMConfigUtil;

/**
 * 码上省后台服务接口
 * 〈一句话功能简述〉<br> 
 * 〈功能详细描述〉
 *
 * @author 15050519
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Controller
@RequestMapping("/mssIn")
public class MssCommodityInController extends DjBaseController  {

    private static final Logger LOGGER = LoggerFactory.getLogger(MssCommodityInController.class);
    
    /**
     * 码上省服务
     */
    @Autowired
    MssCommoditySelfService mssCommoditySelfService;
    
    /**
     * 店员服务
     */
    @Autowired
    StoreManService storeManService;
    
    /**
     * 商品详情服务
     */
    @Autowired
    CommodityDetailRsfService commodityDetailRsfService ;
    
    /**
     * 图片服务
     */
    @Autowired
    UIMGStore uimgStore;
    
    /**
     * 大聚会商品服务
     */
    @Resource
    BppCommodityService bppCommodityService;
    
    /**
     * 查询聚合页详情接口
     */
    @RequestMapping("/saveBpp.do")
    public MyGsonView saveBpp(Principal principal, String activityId, String serviceType,
            String commCode, String mertCode, String gbPrice, String payPrice, String published,
            String categCode) {
        LOGGER.info("saveBpp enter, staffId={}", principal.getName());
        ReturnMsg<BppCommodityInfo> returnMsg = new ReturnMsg<BppCommodityInfo>();
        // 参数校验
        if (StringUtils.isBlank(activityId)) {
            returnMsg.setError(ModelErrorConstant.MODEL_ERR_E001, "入参activityId必填");
        } else if (StringUtils.isBlank(serviceType)) {
            returnMsg.setError(ModelErrorConstant.MODEL_ERR_E001, "入参serviceType必填");
        } else if (StringUtils.isBlank(commCode)) {
            returnMsg.setError(ModelErrorConstant.MODEL_ERR_E001, "入参commCode必填");
        } else if (StringUtils.isBlank(mertCode)) {
            returnMsg.setError(ModelErrorConstant.MODEL_ERR_E001, "入参mertCode必填");
        } else if (StringUtils.isBlank(gbPrice)) {
            returnMsg.setError(ModelErrorConstant.MODEL_ERR_E001, "入参gbPrice必填");
        } else if (StringUtils.isBlank(payPrice)) {
            returnMsg.setError(ModelErrorConstant.MODEL_ERR_E001, "入参payPrice必填");
        } else if (StringUtils.isBlank(published)) {
            returnMsg.setError(ModelErrorConstant.MODEL_ERR_E001, "入参published必填");
        } else if (StringUtils.isBlank(categCode)) {
            returnMsg.setError(ModelErrorConstant.MODEL_ERR_E001, "入参categCode必填");
        }
        // 参数校验异常,返回错误信息
        if (ReturnMsg.FAIL.equals(returnMsg.getRetFlag())) {
            return setGsonView(returnMsg);
        }
        try {
            String categCodes = SCMConfigUtil.getConfig("bppCommodity.receiveCategCodes");
            LOGGER.info("ReceiveBppInf categCodes={}", categCodes);
            List<String> categCodeList = new ArrayList<String>();
            if (StringUtils.isBlank(categCodes)) {
                categCodes = "246;368;584;590;591;437";
            }
            for (String categ : categCodes.split(";")) {
                categCodeList.add(categ);
            }
            if ("5".equals(serviceType)
                    && categCodeList.contains(categCode)) {
                // published 1：手工下架 2：数量卖完下架 0：上架
                if ("0".equals(published)) {
                    Long id = bppCommodityService.judgeIsExsit(activityId);
                    LOGGER.info("ReceiveBppInf old id={}", id);
                    BppCommodityInfo info = new BppCommodityInfo();
                    info.setActivityId(activityId);
                    info.setCategCode(categCode);
                    info.setCommCode(commCode);
                    info.setCreateTime(new Date());
                    info.setGbBeginDate(DateUtils.getFirstDayZeroPointOfMonth(0));
                    info.setGbEndDate(DateUtils.getFirstDayZeroPointOfMonth(1));
                    info.setMertCode(mertCode);
                    info.setPartName("商品" + commCode);
                    info.setPayPrice(payPrice);
                    info.setGbPrice(gbPrice);
                    LOGGER.info("ReceiveBppInf info={}", info);
                    if (id == null) {
                        info.setCreateTime(new Date());
                        bppCommodityService.save(info);
                    } else {
                        info.setId(id);
                        info.setCreateTime(new Date());
                        bppCommodityService.update(info);
                    }
                    returnMsg.setData(info);
                } else {
                    bppCommodityService.delete(activityId);
                }
            }
            
        } catch (Exception e) {
            returnMsg.setError(ErrorCodeConstants.ERR_0002);
            LOGGER.error("saveBpp error,staffId=" + principal.getName(), e);
        }
        return setGsonView(returnMsg);
    }
    
    /**
     * 图片上传接口
     */
    @RequestMapping(value = "/uploadPic.do", produces = "application/json;charset=utf-8")
    @ResponseBody
    public MyGsonView uploadPic(MultipartRequest multipartRequest) {
        LOGGER.info("MssCommodityInController uploadPic");
        MyGsonView gsonView = createGsonView();
        MultipartFile imageFile = multipartRequest.getFile("image");
        // 校验请求
        if (null == imageFile || imageFile.isEmpty() || null == imageFile.getContentType()) {
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0001);
            return gsonView;
        } 
        MediaType mediaType = MediaType.parseMediaType(imageFile.getContentType());
        List<MediaType> supports = MediaType.parseMediaTypes("image/*");
        for (MediaType support : supports) {
            if (support.includes(mediaType)) {
                String imgUrl;
                InputStream in = null;
                try {
                    in = imageFile.getInputStream();
                    imgUrl = uimgStore
                            .onlyUpload(UIMGStore.FileType.MISC, mediaType.getSubtype().toLowerCase(), in);
                    gsonView.addStaticAttribute(BaseContants.DATA, imgUrl);
                } catch (ImageServiceException e) {
                    LOGGER.error("UMIG服务异常ImageServiceException", e);
                    setErrorMsg(gsonView, ErrorCodeConstants.ERR_0002);
                } catch (IOException ex) {
                    LOGGER.error("UMIG服务异常IOException", ex);
                    setErrorMsg(gsonView, ErrorCodeConstants.ERR_0002);
                } catch (Exception ex) {
                    LOGGER.error("UMIG服务异常Exception", ex);
                    setErrorMsg(gsonView, ErrorCodeConstants.ERR_0002);
                } finally {
                    IOUtils.closeQuietly(in);
                }
                break;
            }
            setErrorMsg(gsonView, ErrorCodeConstants.ERR_0001);
        }
        return gsonView;
    }
    
    /**
     * 查询聚合页详情接口
     */
    @RequestMapping("/queryAggregationPage.do")
    public MyGsonView queryAggregationPage(Principal principal) {
        LOGGER.info("queryAggregationPage enter, staffId={}", principal.getName());
        ReturnMsg<MssAggregationPageDto> returnMsg = new ReturnMsg<MssAggregationPageDto>();
        try {
            // 查询聚合页信息
            MssAggregationPageDto page = mssCommoditySelfService.getMssAggregationPageIn();
            returnMsg.setData(page);
        } catch (Exception e) {
            returnMsg.setError(ErrorCodeConstants.ERR_0002);
            LOGGER.error("queryAggregationPage error,staffId=" + principal.getName(), e);
        }
        return setGsonView(returnMsg);
    }
    
    /**
     * 新增或修改聚合页接口
     */
    @RequestMapping("/saveAggregationPage.do")
    public MyGsonView saveAggregationPage(Principal principal, @RequestParam String picUrl, @RequestParam String linkUrl, 
            @RequestParam String beginDate, @RequestParam String endDate, @RequestParam Long id) {
        LOGGER.info("saveAggregationPage enter, staffId={}, picUrl={}, linkUrl={}, beginDate={}, endDate={}, id={}", 
                new Object[] { principal.getName(), picUrl, linkUrl, beginDate, endDate, id });
        ReturnMsg<String> returnMsg = new ReturnMsg<String>();
        // 参数校验
        if (StringUtils.isBlank(picUrl)) {
            returnMsg.setError(ModelErrorConstant.MODEL_ERR_E001, "入参picUrl必填");
        } else if (StringUtils.isBlank(linkUrl)) {
            returnMsg.setError(ModelErrorConstant.MODEL_ERR_E001, "入参linkUrl必填");
        } else if (StringUtils.isBlank(beginDate)) {
            returnMsg.setError(ModelErrorConstant.MODEL_ERR_E001, "入参beginDate必填");
        } else if (StringUtils.isBlank(endDate)) {
            returnMsg.setError(ModelErrorConstant.MODEL_ERR_E001, "入参endDate必填");
        }
        // 参数校验异常,返回错误信息
        if (ReturnMsg.FAIL.equals(returnMsg.getRetFlag())) {
            return setGsonView(returnMsg);
        }
        // 格式时间
        Date bt;
        Date et;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            bt = sdf.parse(beginDate);
        } catch (ParseException e) {
            LOGGER.error("parse beginDate find wrong.", e);
            returnMsg.setError(ModelErrorConstant.MODEL_ERR_E001, "入参beginDate格式错误");
            return setGsonView(returnMsg);
        }
        try {
            et = sdf.parse(endDate);
        } catch (ParseException e) {
            LOGGER.error("parse endDate find wrong.", e);
            returnMsg.setError(ModelErrorConstant.MODEL_ERR_E001, "入参endDate格式错误");
            return setGsonView(returnMsg);
        }
        // 处理聚合页信息
        try {
            MssAggregationPage mssPage = new MssAggregationPage();
            mssPage.setLinkUrl(linkUrl);
            mssPage.setPicUrl(picUrl);
            mssPage.setBeginDate(bt);
            mssPage.setEndDate(et);
            if (null != id && id > 0) {
                mssPage.setId(id);
                mssCommoditySelfService.update(mssPage);
            } else {
                // 防止异常问题导致没有ID,故查询一遍
                MssAggregationPageDto hasPage = mssCommoditySelfService.getMssAggregationPageIn();
                if (null != hasPage && hasPage.getId() > 0) {
                    mssPage.setId(hasPage.getId());
                    mssCommoditySelfService.update(mssPage);
                } else {
                    // 查询聚合页信息
                    mssCommoditySelfService.save(mssPage);
                }
            }
            returnMsg.setData("OK");
        } catch (Exception e) {
            // 处理异常
            if (null != id && id > 0) {
                returnMsg.setError(ErrorCodeConstants.ERR_0041);
            } else {
                returnMsg.setError(ErrorCodeConstants.ERR_0040);
            }
            LOGGER.error("saveAggregationPage error,staffId=" + principal.getName(), e);
        }
        return setGsonView(returnMsg);
    }
    
    /**
     * 查询码上省品类数据 功能描述: <br>
     * SCM配置 〈功能详细描述〉
     *
     * @param principal
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryCateList.do")
    public MyGsonView queryCateList(Principal principal) {
        LOGGER.info("queryCateList enter, staffId={}", principal.getName());
        ReturnMsg<Map<String, Object>> returnMsg = new ReturnMsg<Map<String, Object>>();
        try {
            List<MssCategory> list = mssCommoditySelfService.queryCateList();
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("list", list);
            returnMsg.setData(data);
        } catch (Exception e) {
            returnMsg.setError(ErrorCodeConstants.ERR_0002);
            LOGGER.error("queryCateList error,staffId=" + principal.getName(), e);
        }
        return setGsonView(returnMsg);
    }
    
    /**
     * 分页查询商品接口
     */
    @RequestMapping("/queryCommodityPage.do")
    public MyGsonView queryCommodityPage(Principal principal, String commCode, String typeId, String cateCode, Integer pageNo,
            Integer pageSize) {
        LOGGER.info("queryCommodityPage enter, principal={},commCode={},typeId={},cateCode={},pageNo={},pageSize={}",
                new Object[] { principal.getName(), commCode, typeId, cateCode, pageNo, pageSize });
        ReturnMsg<MssCommodityPageResponse> returnMsg = new ReturnMsg<MssCommodityPageResponse>();
        try {
            // 查询商品信息
            MssCommodityPageResponse resp = mssCommoditySelfService.queryCommodityInfoListIn(
                    DJStringUtils.initCurrIndex(pageNo, pageSize), DJStringUtils.initPageSize(pageSize), typeId, cateCode,
                    commCode);
            returnMsg.setData(resp);
        } catch (Exception e) {
            returnMsg.setError(ErrorCodeConstants.ERR_0002);
            LOGGER.error("queryCommodityPage error,staffId=" + principal.getName() + ",typeId=" + typeId, e);
        }
        return setGsonView(returnMsg);
    }
    
    /**
     * 删除商品接口
     */
    @RequestMapping("/deleteCommById.do")
    public MyGsonView deleteCommById(Principal principal, Long id) {
        LOGGER.info("deleteCommById enter, staffId={}, id={}", principal.getName(), id);
        ReturnMsg<String> returnMsg = new ReturnMsg<String>();
        // 参数校验
        if (null == id || id < 1) {
            returnMsg.setError(ModelErrorConstant.MODEL_ERR_E001, "入参id必填");
            return setGsonView(returnMsg);
        }
        try {
            mssCommoditySelfService.delCommodityById(id);
        } catch (Exception e) {
            returnMsg.setError(ErrorCodeConstants.ERR_0038);
            LOGGER.error("deleteCommById error,staffId=" + principal.getName() + ",id" + id, e);
        }
        return setGsonView(returnMsg);
    }
    
    /**
     * 添加商品接口
     */
    @RequestMapping("/saveComm.do")
    public MyGsonView saveComm(Principal principal, String commCode, String mertCode,
            String typeId, String cateCode, String beginDate, String endDate) {
        LOGGER.info("saveComm enter,staffId={},commCode={},mertCode={},typeId={},cateCode={},beginDate={},endDate={}", 
               new Object[]{principal.getName(), commCode, mertCode, typeId, cateCode, beginDate, endDate});
        ReturnMsg<String> returnMsg = new ReturnMsg<String>();
        // 入参非空判断
        if (StringUtils.isBlank(commCode)) {
            returnMsg.setError(ModelErrorConstant.MODEL_ERR_E001, "入参commCode必填");
        } else if (StringUtils.isBlank(mertCode)){
            returnMsg.setError(ModelErrorConstant.MODEL_ERR_E001, "入参mertCode必填");
        } else if (StringUtils.isBlank(typeId)){
            returnMsg.setError(ModelErrorConstant.MODEL_ERR_E001, "入参typeId必填");
        } else if (StringUtils.isBlank(cateCode)){
            returnMsg.setError(ModelErrorConstant.MODEL_ERR_E001, "入参cateCode必填");
        } else if (StringUtils.isBlank(beginDate)){
            returnMsg.setError(ModelErrorConstant.MODEL_ERR_E001, "入参beginDate必填");
        } else if (StringUtils.isBlank(endDate)){
            returnMsg.setError(ModelErrorConstant.MODEL_ERR_E001, "入参endDate必填");
        }
        // 参数校验异常,返回错误信息
        if (ReturnMsg.FAIL.equals(returnMsg.getRetFlag())) {
            return setGsonView(returnMsg);
        }
        Date bd;
        Date ed;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            bd = sdf.parse(beginDate);
        } catch (ParseException e) {
            LOGGER.error("parse beginDate find wrong.", e);
            returnMsg.setError(ModelErrorConstant.MODEL_ERR_E001, "入参beginDate格式错误");
            return setGsonView(returnMsg);
        }
        try {
            ed = sdf.parse(endDate);
        } catch (ParseException e) {
            LOGGER.error("parse endDate find wrong.", e);
            returnMsg.setError(ModelErrorConstant.MODEL_ERR_E001, "入参endDate格式错误");
            return setGsonView(returnMsg);
        }
        // 查询商品详情
        SNItemInfoResponseDTO dto = commodityDetailRsfService.queryProductBD(commCode);
        // 为空时,返回错误信息
        if (null == dto) {
            returnMsg.setError(ModelErrorConstant.MODEL_ERR_E001, "查询无此商品,请检查");
            return setGsonView(returnMsg);
        }
        try {
            MssCommoditySelf commodity = new MssCommoditySelf();
            commodity.setCommCode(commCode);
            commodity.setMertCode(mertCode);
            commodity.setPartName(StringUtils.isBlank(dto.getItemDisplayName()) ? dto.getItemName() : dto.getItemDisplayName());
            commodity.setTypeId(typeId);
            commodity.setCateCode(cateCode);
            commodity.setBeginDate(bd);
            commodity.setEndDate(ed);
            // 查询库中是否存在该商品信息
            MssCommoditySelf hasImport = mssCommoditySelfService.getCommodityByCommCode(commCode, mertCode);
            // 存在则更新商品信息
            if (null != hasImport && hasImport.getId() > 0) {
                commodity.setId(hasImport.getId());
                mssCommoditySelfService.update(commodity);
            } else {
                // 保存商品信息
                mssCommoditySelfService.save(commodity);
            }
        } catch (Exception e) {
            returnMsg.setError(ErrorCodeConstants.ERR_0039);
            LOGGER.error("saveComm error,staffId=" + principal.getName() + ",commCode=" + commCode, e);
        }
        return setGsonView(returnMsg);
    }
    
    /**
     * 导入商品接口
     */
    @RequestMapping("/importMssCommodity.do")
    public MyGsonView importMssCommodity(
            @RequestParam(value = "file", required = true) MultipartFile file) {
        LOGGER.info("importMssCommodity enter");
        ReturnMsg<String> ret = new ReturnMsg<String>();
        // 创建对Excel工作簿文件的引用
        Workbook wookbook = null;
        try {
            wookbook = ExcelUtils.createWb(file);
            // 默认取第一个sheet
            Sheet sheet = wookbook.getSheetAt(0);
            String msg = mssCommoditySelfService.importCommodityFile(sheet);
            // 导入描述不为空时返回
            if (StringUtils.isNotBlank(msg)) {
                ret.setData(msg);
            }
        } catch (IOException e) {
            LOGGER.error("导入码上省商品出错", e);
            ret.setError(ErrorCodeConstants.MAIN_PUSH_ERR_E007,
                    ErrorCodeConstants.MAIN_PUSH_ERR_MAP);
        } catch (Exception e) {
            LOGGER.error("导入码上省商品失败", e);
            ret.setError(ErrorCodeConstants.MAIN_PUSH_ERR_E007,
                    ErrorCodeConstants.MAIN_PUSH_ERR_MAP);
        }
        return setGsonView(ret);
    }
}
